import 'package:flutter/material.dart';

//轮播图
import 'package:flutter/widgets.dart';
import 'package:flutter_jd_shop/model/ProductModel.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

//动态适配宽高
import '../../services/ScreenAdapter.dart';

//网络请求层
import '../../config/Config.dart';
import 'package:dio/dio.dart';

//model层
import '../../model/FocusModel.dart';


class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>  with AutomaticKeepAliveClientMixin{

  @override
  //保持页面持久化
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _getFocusData();
    _getHotProductData();
    _getBestProductData();
  }
  //标题
  Widget _titleWidget(value) {
    return Container(
      height: ScreenAdapter.height(32),
      margin: EdgeInsets.only(left: ScreenAdapter.width(20)), //设置丨 左边的距离
      padding: EdgeInsets.only(left: ScreenAdapter.width(20)),//设置文字内容(child)往左一点
      //左边设置一个丨  用背景来写
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
                color: Colors.red,
                width: ScreenAdapter.width(10),
              )
          )
      ),

      child: Text(
        value,
        style: TextStyle(color: Colors.black87),
      ),
    );
  }


  //首页轮播图 start
  List _focusData = [];
  _getFocusData() async{
    var api='${Config.domain}api/focus';
    var result = await Dio().get(api);
    var focusList = FocusModel.fromJson(result.data);
    setState(() {
      this._focusData = focusList.result;
    });
  }
  Widget _swiperWidget() {
    if(this._focusData.length>0){
      return Container(
        child: AspectRatio(
          aspectRatio: 2/1,//设置图片比例，宽是高的一倍
          child: Swiper(
            itemBuilder: (BuildContext context, int index) {

              //对pic路径处理为https可请求的
              String pic =this._focusData[index].pic;
              pic=Config.domain+pic.replaceAll('\\', '/');

              return new Image.network(
                pic,
                fit: BoxFit.fill,
              );
            },
            itemCount: this._focusData.length,
            pagination: new SwiperPagination(),
            autoplay: true,//自动轮播
          ),
        ),
      );
    }else{
      return Container(
        child: Center(
          child: CircularProgressIndicator(), //加载请求转圈圈的样式
        ),
      );
    }
  }
  //首页轮播图 end


  //猜你喜欢 start
  List _hotProductList = [];
  _getHotProductData() async{
    var api = '${Config.domain}api/plist?is_hot=1';
    var result = await Dio().get(api);
    var hotProductList = ProductModel.fromJson(result.data);
    setState(() {
      this._hotProductList = hotProductList.result;
    });
  }
  Widget _hotProductListWidget() {
    if(this._hotProductList.length>0){
      return Container(
        height: ScreenAdapter.height(220),//计算下所需要的高 20*2+140+40
        padding: EdgeInsets.all(ScreenAdapter.width(20)), //设置容器内的child四边边距
        child: ListView.builder(
          scrollDirection: Axis.horizontal,//水平垂直，往左右方向拓展
          itemBuilder: (contxt, index) {
            //处理图片
            String sPic = this._hotProductList[index].sPic;
            sPic = Config.domain + sPic.replaceAll('\\', '/');

            //价格
            dynamic sPrice=this._hotProductList[index].price;
            return Column(
              children: <Widget>[
                Container(
                  height: ScreenAdapter.height(140),
                  width: ScreenAdapter.width(150),
                  margin: EdgeInsets.only(right: ScreenAdapter.width(21)),//设置容器的外右边距离
                  child: Image.network(
                      sPic,
                      fit: BoxFit.cover),
                ),
                Container(
                  padding: EdgeInsets.only(top: ScreenAdapter.height(10)),
                  height: ScreenAdapter.height(40),
                  child: Text(
                      "￥ ${sPrice}",
                      style: TextStyle(
                        color: Colors.red,
                      ),
                  ),
                )
              ],
            );
          },
          itemCount: 10,
        ),
      );
    }else{
      return Container(
        child: Center(
          child: CircularProgressIndicator(), //加载请求转圈圈的样式
        ),
      );
    }
  }
  //猜你喜欢 end


  //热门推荐 start
  List _bestProductList = [];
  _getBestProductData() async {
    var api = '${Config.domain}api/plist?is_best=1';
    var result = await Dio().get(api);
    var bestProductList = ProductModel.fromJson(result.data);
    setState(() {
      this._bestProductList = bestProductList.result;
    });
  }
  Widget _recProductListWidget(){
    if(this._bestProductList.length>0){
      //计算wrap的距离 计算公式如下 获取屏幕的宽 减去容器的宽度 然后/2 因为一排放两个图片
      var itemWidth=(ScreenAdapter.getScreenWidth()-30)/2;
      return Container(
        //设置这个容器的外边距 // padding: EdgeInsets.all(ScreenAdapter.height(10)),
        padding: EdgeInsets.only(
          top:ScreenAdapter.height(10),
          right: ScreenAdapter.height(14),
          left: ScreenAdapter.height(14),
          bottom: ScreenAdapter.height(10),
        ),

        child: Wrap(//Wrap会自动布局
          spacing: ScreenAdapter.width(10),//设置中间的距离
          runSpacing: ScreenAdapter.width(10),//设置wrap的间距的下距离

          //循环处理数据
          children: this._bestProductList.map((value){
            //图片
            String sPic=value.sPic;
            sPic=Config.domain+sPic.replaceAll('\\', '/');

            return Container(
              padding: EdgeInsets.all(10),
              width: itemWidth,
              decoration: BoxDecoration(
                border:
                Border.all(color:Color.fromRGBO(233, 233, 233, 0.9),width: ScreenAdapter.width(2) ),
              ),
              child: Column(
                children: [
                  //主图
                  Container(
                      width: double.infinity,//宽度自适应
                      child:AspectRatio(
                        aspectRatio: 1/1,//预防服务端返回的图片宽高不一致
                        child: Image.network(
                          sPic,
                          fit: BoxFit.cover,
                        ),
                      )
                  ),

                  //商品标题
                  Padding(
                    padding: EdgeInsets.only(
                        top: ScreenAdapter.height(5)
                    ),
                    child: Text(
                      '${value.title}',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,//多出两行显示...
                      style: TextStyle(
                          color: Colors.black54
                      ),
                    ),
                  ),

                  //价格
                  Padding(
                    padding: EdgeInsets.only(top: ScreenAdapter.height(5)),
                    child: Stack(
                      children: [
                        Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '${value.price}',
                            style: TextStyle(
                              color: Colors.red,
                              fontSize: 16,
                            ),
                          ),
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: Text(
                            '${value.oldPrice}',
                            style: TextStyle(
                              color: Colors.black54,
                              fontSize: 15,
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
        ),
      );
    }else{
      return Container(
        child: Center(
          child: CircularProgressIndicator(), //加载请求转圈圈的样式
        ),
      );
    }
  }
  //热门推荐 end

  @override
  Widget build(BuildContext context) {

    //配合ScreenAdapter取宽高
    ScreenAdapter.init(context);

    return  ListView(
      children: <Widget>[
        //1、轮播图
        _swiperWidget(),

        //2、猜你喜欢
        SizedBox(height: ScreenAdapter.height(20)),
        _titleWidget("猜你喜欢"),
        _hotProductListWidget(),

        //3、热门推荐
        _titleWidget("热门推荐"),
        _recProductListWidget(),
        
      ],
    );
  }

}